import weibo from './utils/services'
import { WEIBO_LIST, ADD_WEIBO, DEL_WEIBO, PRAISE_WEIBO } from './utils/types'

export default ({ scope, ...options }) => {
  weibo.setOption(options)

  const state = {
    weiboList: []
  }

  const getters = {
    weiboList: state => state.weiboList,
    hasPublish: state => state.weiboList.filter(item => item.userName === '235022').length > 0
  }

  const actions = {
    getWeiboList ({ commit }, { body, then, err }) {
      return weibo.getWeiboList(body).then(...then).then(data => {
        commit(WEIBO_LIST, data)
      }).catch(...err)
    },
    addWeibo ({ commit }, { body, then, err }) {
      return weibo.addWeibo(body).then(...then).then(data => {
        commit(ADD_WEIBO, data)
      }).catch(...err)
    },
    deleteWeibo ({ commit }, { body, then, err }) {
      return weibo.deleteWeibo(body).then(...then).then(data => {
        commit(DEL_WEIBO, data)
      }).catch(...err)
    },
    praiseWeibo ({ commit }, { body, then, err }) {
      return weibo.praiseWeibo(body).then(...then).then(data => {
        commit(PRAISE_WEIBO, data)
      }).catch(...err)
    }
  }

  const mutations = {
    [WEIBO_LIST] (state, mutation) {
      state.weiboList = mutation
    }, [ADD_WEIBO] (state, mutation) {
      Object.assign(state, mutation)
    }, [DEL_WEIBO] (state, mutation) {
      Object.assign(state, mutation)
    }, [PRAISE_WEIBO] (state, mutation) {
      state = Object.assign({}, state, mutation)
    }
  }
  return { state, getters, actions, mutations }
}
